package com.gmd.historiaclinica.model.repository;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.gmd.historiaclinica.model.dao.HistoriaclinicaDAO;
import com.gmd.model.Historiaclinica;

public class JPAHistoriaclinicaDAO implements HistoriaclinicaDAO{

	EntityManager em;
	
	public JPAHistoriaclinicaDAO(EntityManager em){
		this.em = em;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Historiaclinica> findAll() {
		List<Historiaclinica> result;
		Query q = em.createNamedQuery("findAllHisto");
		result = q.getResultList();
		return (result != null) ?  result : new ArrayList<Historiaclinica>();
	}

	@Override
	public Historiaclinica findById(Integer id) {
		return em.find(Historiaclinica.class, id);
	}

	@Override
	public Historiaclinica findByNroDoc(String nrodoc) {
		Query q = em.createNamedQuery("findByNroDocHisto");
		q.setParameter("nrodoc", nrodoc);
		Object result = q.getSingleResult();
		return (result !=  null) ? (Historiaclinica) result : null;
	}

	@Override
	public Historiaclinica insert(Historiaclinica o) {
		em.persist(o);
		return o;
	}

	@Override
	public int getLastId() {
        Query query = em.createNamedQuery("getLastIdHisto");
		Object result = query.getSingleResult();
		return (result != null) ? (Integer) result : 0;
	}

}
